package org.ece3574.WTParty;


import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MapScreenActivity extends MapActivity implements OnClickListener{
	
	private MapView mapView;
	private Button searchBtn;
	private EditText searchAddr;
	private View viewBubble;
	private MyMapOverlay itemizedoverlay;
	//private ViewGroup parentBubble;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapscreen);
        
		mapView = (MapView) findViewById(R.id.mapview);
		searchBtn = (Button) findViewById(R.id.Button01);
		
		searchAddr = (EditText) findViewById(R.id.EditText01);

		mapView.setSatellite(true);
		mapView.setBuiltInZoomControls(true);
		
		searchBtn.setOnClickListener(this);
		
		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.point);
		itemizedoverlay = new MyMapOverlay(drawable, this);
		mapOverlays.add(itemizedoverlay);
    }
    
	private class MyMapOverlay extends MapOverlay
	{

		public MyMapOverlay(Drawable defaultMarker, Context context) {
			super(defaultMarker, context);
		}
		
		// Overlay on tap
		@Override
		protected boolean onTap(int index) {
			OverlayItem item = mOverlays.get(index);
			addBubble(new GeoLocation(item.getSnippet(), item.getPoint().getLatitudeE6(), item.getPoint().getLongitudeE6()));
			
			return true;
		}
		
	}
    
    
    
    // Search button action
    public void onClick(View v) {
		String inputAddr = searchAddr.getText().toString();
		new AsyncGeocode().execute(inputAddr);

	}
    
    private class AsyncGeocode extends AsyncTask<String, Void, GeoLocation>
    {

		@Override
		protected GeoLocation doInBackground(String... inputAddr) {
			GeoLocation location = WebServiceClient.geoCode(inputAddr[0]);
			return location;
		}
		
		protected void onPostExecute(GeoLocation location)
		{
			displaySearchedLocation(location);

		}
    	
    }
    
    public void displaySearchedLocation(GeoLocation location)
    {
		if (location!=null)
		{
			setMarker(location);
			closeKB();
			searchAddr.setText("");
			addBubble(location);
			navigateToLocation(location.latitude,location.longitude, mapView);
		}
		else {
			Dialog searchError = new AlertDialog.Builder(
					MapScreenActivity.this).setIcon(0)
					.setTitle("Search Error")
					.setPositiveButton(android.R.string.ok, null)
					.setMessage("Address not found.")
					.create();
			searchError.show();
		}
    }
    
    // Close keyboard after search button is pressed
    private void closeKB()
    {
    	InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(searchAddr.getWindowToken(), 0);
    }
    // Sets marker on the searched location
	private void setMarker(GeoLocation loc) {

		GeoPoint point = new GeoPoint(loc.latitude, loc.longitude);
		OverlayItem overlayitem = new OverlayItem(point, "Location:", loc.name);
		itemizedoverlay.addOverlay(overlayitem);
		
	}
	
    
    // Focuses on a location based on lat. and long.
    protected static void navigateToLocation(double latitude, double longitude,
			MapView view) {
		GeoPoint point = new GeoPoint((int) latitude, (int) longitude);
		view.displayZoomControls(true);
		MapController control = view.getController();
		control.animateTo(point);
		int zoom = view.getMaxZoomLevel();
		control.setZoom(zoom - 2);
	}
    // Text Bubble Adder
	private void addBubble(GeoLocation loc) {
		GeoPoint point = new GeoPoint(loc.latitude, loc.longitude);
		//if (viewBubble == null) {
			ViewGroup parentBubble = (ViewGroup) mapView.getParent();
			if(viewBubble!=null)
			{
				mapView.removeView(viewBubble);
				viewBubble = null;
			}
			viewBubble = getLayoutInflater().inflate(R.layout.popbub,
					parentBubble, false);
			MapView.LayoutParams mvlp = new MapView.LayoutParams(
					MapView.LayoutParams.WRAP_CONTENT,
					MapView.LayoutParams.WRAP_CONTENT, point, -127, -170,
					MapView.LayoutParams.LEFT);
			FrameLayout f = (FrameLayout) viewBubble;
			((TextView) f.findViewById(R.id.bubbleText))
					.setText(loc.name);
			//mapView.setBuiltInZoomControls(false);
			viewBubble.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					mapView.removeView(viewBubble);
					viewBubble = null;
					mapView.setBuiltInZoomControls(true);
				}
			});
			mapView.addView(viewBubble, mvlp);

		//}
	}
    
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}

